// src/recipe-detail/RecipeDetail.tsx
import React, { useState, useEffect } from 'react';
import { Layout, Card, Row, Col, Spin, message, Button, Tag, Typography} from 'antd';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import Sidebar from '../Sidebar';
import RecipeAuthorCard from './RecipeAuthorCard';
import RecipeSteps from './RecipeSteps';
import RecipeComments from './RecipeComments';

import {ArrowLeftOutlined, StarOutlined, StarFilled } from '@ant-design/icons';

const { Content } = Layout;
const { Title, Paragraph } = Typography;
const currentUserId = localStorage.getItem('userId');

interface RecipeFromList {
  id: string;
  title: string;
  coverImage: string;
  userId?: number;
  category?: string;
  tags?: string[];
  updatedAt?: string;
  favoriteCount?: number;
  [key: string]: any;
}

// 颜色配置 - 与消息页面保持一致
const colorConfig = {
  primary: '#e8d9c7', // 主色调 - 浅棕色
  primaryDark: '#8b4513', // 深棕色 - 文字颜色
  border: '#d4b896', // 边框色
  background: '#f8f4f0', // 背景色
  badge: '#a0522d', // 徽章颜色
  tabActive: '#e8d9c7', // 标签页激活颜色
};

const RecipeDetail: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const location = useLocation();
  const [recipe, setRecipe] = useState<RecipeFromList | null>(null);
  const [loading, setLoading] = useState<boolean>(true);

  const [categories, setCategories] = useState<{ id: number; name: string }[]>([]);
  const [tags, setTags] = useState<{ id: number; name: string }[]>([]);
  const [ingredients, setIngredients] = useState<{ amount: number; ingredient: { name: string; unit: string } }[]>([]);
  const [steps, setSteps] = useState<any[]>([]);
  
  // 作者信息和关注状态
  const [authorInfo, setAuthorInfo] = useState<{
    id: number;
    username: string;
    nickname: string;
    avatar?: string;
  } | null>(null);
  const [isFollowingAuthor, setIsFollowingAuthor] = useState<boolean>(false);
  const [followLoading, setFollowLoading] = useState<boolean>(false);

  // 收藏状态
  const [isFavorite, setIsFavorite] = useState<boolean>(false);
  const [favoriteLoading, setFavoriteLoading] = useState<boolean>(false);
  const [currentFavoriteCount, setCurrentFavoriteCount] = useState<number>(0);

  // 图片URL处理函数
  const getImageUrl = (imagePath: string) => {
    if (!imagePath) {
      return 'https://via.placeholder.com/400x200?text=无图';
    }
    
    // 如果已经是完整URL，直接返回
    if (imagePath.startsWith('http')) {
      return imagePath;
    }
    
    // 如果是相对路径，拼接基础URL
    return `http://218.244.141.86:8080${imagePath}`;
  };

  // 处理分类标签点击 - 跳转到分类菜谱列表页面
  const handleCategoryClick = (categoryName: string) => {
    navigate(`/category/${encodeURIComponent(categoryName)}`);
  };

  // 处理标签点击 - 跳转到标签菜谱列表页面
  const handleTagClick = (tagName: string) => {
    navigate(`/tag/${encodeURIComponent(tagName)}`);
  };

  // 创建浏览记录的函数
  const createBrowseRecord = async (recipeId: number) => {
    try {
      const token = localStorage.getItem('token');
      const userId = localStorage.getItem('userId');
      
      if (!token || !userId) {
        console.log('用户未登录，跳过创建浏览记录');
        return;
      }

      const response = await fetch(`/api/browse?userId=${userId}&recipeId=${recipeId}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      });

      if (response.ok) {
        console.log('浏览记录创建成功');
      } else {
        console.warn('创建浏览记录失败:', response.status);
      }
    } catch (error) {
      console.error('创建浏览记录出错:', error);
    }
  };

  // 获取作者信息的函数
  const fetchAuthorInfo = async (authorId: number) => {
    try {
      const token = localStorage.getItem('token');
      if (!token) return;

      console.log('开始获取作者信息，作者ID:', authorId);

      // 尝试多个可能的用户信息接口
      const endpoints = [
        `/api/users/${authorId}`,
        `/api/users/search?uid=${authorId}`,
        `/api/user/${authorId}/profile`
      ];

      let authorDataFound = null;

      for (const endpoint of endpoints) {
        try {
          console.log('尝试用户信息接口:', endpoint);
          const response = await fetch(endpoint, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });

          if (response.ok) {
            const userData = await response.json();
            console.log('用户信息响应:', userData);
            
            const actualData = Array.isArray(userData) ? userData[0] : userData;
            
            if (actualData) {
              const username = actualData.username || actualData.account || actualData.nickname || `用户${authorId}`;
              const nickname = actualData.nickname || actualData.name || username;
              
              const BASE_URL = "http://218.244.141.86:8080";

              // 安全处理头像路径
              const fixUrl = (path?: string) => {
                if (!path) return undefined;
                if (path.startsWith('http')) return path;
                return `${BASE_URL}${path}`;
              };

              authorDataFound = {
                id: actualData.id || actualData.userId || authorId,
                username: username,
                nickname: nickname,
                avatar: fixUrl(actualData.avatar || actualData.avatarUrl),
              };
              console.log('找到作者信息:', authorDataFound);
              break;
            }
          } else {
            console.warn(`用户信息接口 ${endpoint} 返回错误:`, response.status);
          }
        } catch (error) {
          console.warn(`用户信息接口 ${endpoint} 失败:`, error);
          continue;
        }
      }

      if (authorDataFound) {
        setAuthorInfo(authorDataFound);
      } else {
        // 如果所有接口都失败，使用默认数据
        const defaultAuthor = {
          id: authorId,
          username: `用户${authorId}`,
          nickname: `用户${authorId}`,
        };
        console.log('使用默认作者信息:', defaultAuthor);
        setAuthorInfo(defaultAuthor);
      }
    } catch (error) {
      console.error('获取作者信息失败:', error);
      const fallbackAuthor = {
        id: authorId,
        username: `用户${authorId}`,
        nickname: `用户${authorId}`,
      };
      setAuthorInfo(fallbackAuthor);
    }
  };

  // 检查关注状态
  const checkFollowingStatus = async (authorId: number) => {
    try {
      const token = localStorage.getItem('token');
      const currentUserId = localStorage.getItem('userId');
      
      if (!token || !currentUserId) {
        console.log('用户未登录，跳过检查关注状态');
        return;
      }
  
      const currentUserIdNum = parseInt(currentUserId);
      
      console.log('检查关注状态参数:', {
        followerId: currentUserIdNum,
        followeeId: authorId
      });
  
      // 方法1: 使用获取用户关注列表的API来判断
      try {
        const response = await fetch(`/api/userfollows/follower/${currentUserIdNum}/followees`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });
  
        console.log('关注列表响应状态:', response.status);
  
        if (response.ok) {
          const followings = await response.json();
          console.log('用户关注列表:', followings);
          
          // 检查是否关注了目标作者
          const isFollowing = Array.isArray(followings) && followings.some((following: any) => 
            following.followeeId === authorId
          );
          
          console.log('通过关注列表判断的关注状态:', isFollowing);
          setIsFollowingAuthor(isFollowing);
          return;
        }
      } catch (error) {
        console.warn('通过关注列表检查失败:', error);
      }
  
      // 方法2: 如果方法1失败，尝试获取所有关注关系
      try {
        const response = await fetch(`/api/userfollows`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });
  
        if (response.ok) {
          const allFollows = await response.json();
          console.log('所有关注关系:', allFollows);
          
          // 检查是否存在当前用户关注目标作者的关系
          const isFollowing = Array.isArray(allFollows) && allFollows.some((follow: any) => 
            follow.followerId === currentUserIdNum && follow.followeeId === authorId
          );
          
          console.log('通过所有关注关系判断的关注状态:', isFollowing);
          setIsFollowingAuthor(isFollowing);
          return;
        }
      } catch (error) {
        console.warn('通过所有关注关系检查失败:', error);
      }
  
      // 如果以上方法都失败，设置为未关注状态
      console.log('所有关注状态检查方法都失败，默认设置为未关注');
      setIsFollowingAuthor(false);
      
    } catch (error) {
      console.error('检查关注状态失败:', error);
      setIsFollowingAuthor(false);
    }
  };
  

  // 改进的收藏状态检查函数
  const checkFavoriteStatus = async (recipeId: number) => {
    try {
      const token = localStorage.getItem('token');
      const userId = localStorage.getItem('userId');
      
      if (!token || !userId) {
        console.log('用户未登录，跳过检查收藏状态');
        return;
      }

      const userIdNum = parseInt(userId);

      // 尝试多个可能的检查收藏状态的接口
      const endpoints = [
        `/api/favorites/check?userId=${userIdNum}&recipeId=${recipeId}`,
        `/api/favorites/user/${userIdNum}/recipe/${recipeId}`,
      ];

      for (const endpoint of endpoints) {
        try {
          console.log('检查收藏状态，尝试端点:', endpoint);
          const response = await fetch(endpoint, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });

          if (response.ok) {
            const result = await response.json();
            console.log('收藏状态检查结果:', result);
            
            // 处理不同的响应格式
            if (typeof result === 'boolean') {
              setIsFavorite(result);
              break;
            } else if (result.isFavorite !== undefined) {
              setIsFavorite(result.isFavorite);
              break;
            } else if (result.exists !== undefined) {
              setIsFavorite(result.exists);
              break;
            } else if (result.data !== undefined) {
              setIsFavorite(result.data);
              break;
            }
          }
        } catch (error) {
          console.warn(`收藏状态检查端点 ${endpoint} 失败:`, error);
          continue;
        }
      }

      // 如果所有检查接口都失败，回退到获取用户收藏列表
      await fetchUserFavorites(recipeId);
    } catch (error) {
      console.error('检查收藏状态失败:', error);
      await fetchUserFavorites(recipeId);
    }
  };

  // 获取用户收藏列表来检查收藏状态
  const fetchUserFavorites = async (targetRecipeId: number) => {
    try {
      const token = localStorage.getItem('token');
      const userId = localStorage.getItem('userId');
      
      if (!token || !userId) return;

      const userIdNum = parseInt(userId);
      const endpoints = [
        `/api/favorites/user/${userIdNum}`,
        `/api/users/${userIdNum}/favorites`,
      ];

      for (const endpoint of endpoints) {
        try {
          console.log('获取用户收藏列表，尝试端点:', endpoint);
          const response = await fetch(endpoint, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });

          if (response.ok) {
            const favorites = await response.json();
            console.log('用户收藏列表:', favorites);
            
            // 处理不同的响应格式
            let favoriteList = favorites;
            if (favorites.data) favoriteList = favorites.data;
            if (favorites.list) favoriteList = favorites.list;
            
            const isFav = Array.isArray(favoriteList) && favoriteList.some((fav: any) => 
              fav.recipeId === targetRecipeId || 
              fav.id === targetRecipeId ||
              (fav.recipe && fav.recipe.id === targetRecipeId)
            );
            console.log('是否收藏:', isFav);
            setIsFavorite(isFav);
            break;
          }
        } catch (error) {
          console.warn(`收藏列表端点 ${endpoint} 失败:`, error);
          continue;
        }
      }
    } catch (error) {
      console.error('获取用户收藏列表失败:', error);
    }
  };

  // 改进的关注/取消关注函数
const handleFollowAuthor = async () => {
  if (!authorInfo) return;

  setFollowLoading(true);
  try {
    const token = localStorage.getItem('token');
    const currentUserId = localStorage.getItem('userId');
    
    if (!token || !currentUserId) {
      message.warning('请先登录');
      return;
    }

    const currentUserIdNum = parseInt(currentUserId);

    console.log('关注操作:', {
      currentUserId: currentUserIdNum,
      authorId: authorInfo.id,
      current状态: isFollowingAuthor
    });

    if (isFollowingAuthor) {
      // 取消关注 - 使用DELETE接口
      const response = await fetch(`/api/userfollows/${currentUserIdNum}/${authorInfo.id}`, {
        method: 'DELETE',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      console.log('取消关注响应状态:', response.status);

      if (response.ok) {
        setIsFollowingAuthor(false);
        message.success('已取消关注');
      } else {
        const errorText = await response.text();
        console.error('取消关注失败:', response.status, errorText);
        message.error('取消关注失败');
        // 操作失败后重新检查实际状态
        checkFollowingStatus(authorInfo.id);
      }
    } else {
      // 关注 - 使用POST接口
      const response = await fetch(`/api/userfollows`, {
        method: 'POST',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          followerId: currentUserIdNum,
          followeeId: authorInfo.id
        }),
      });

      console.log('关注响应状态:', response.status);

      if (response.ok) {
        setIsFollowingAuthor(true);
        message.success('关注成功');
      } else {
        const errorText = await response.text();
        console.error('关注失败:', response.status, errorText);
        message.error('关注失败');
        // 操作失败后重新检查实际状态
        checkFollowingStatus(authorInfo.id);
      }
    }
  } catch (error) {
    message.error('操作失败');
    console.error('关注操作异常:', error);
  } finally {
    setFollowLoading(false);
  }
};

  // 改进的收藏/取消收藏函数
  const handleFavorite = async () => {
    if (!recipe) return;

    setFavoriteLoading(true);
    try {
      const token = localStorage.getItem('token');
      const userId = localStorage.getItem('userId');
      
      if (!token || !userId) {
        message.warning('请先登录');
        return;
      }

      const recipeId = parseInt(recipe.id);
      const userIdNum = parseInt(userId);

      console.log('收藏操作:', { userId: userIdNum, recipeId, isFavorite });

      if (isFavorite) {
        // 取消收藏
        const response = await fetch(`/api/favorites?userId=${userIdNum}&recipeId=${recipeId}`, {
          method: 'DELETE',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });

        if (response.ok) {
          setIsFavorite(false);
          setCurrentFavoriteCount(prev => Math.max(0, prev - 1));
          message.success('已取消收藏');
        } else {
          const errorText = await response.text();
          console.error('取消收藏失败:', response.status, errorText);
          message.error(`取消收藏失败: ${response.status}`);
        }
      } else {
        // 收藏 - 尝试不同的参数格式
        const endpoints = [
          `/api/favorites?userId=${userIdNum}&recipeId=${recipeId}`,
          `/api/favorites`,
        ];

        let success = false;
        
        for (const endpoint of endpoints) {
          try {
            console.log('尝试收藏端点:', endpoint);
            const requestOptions: RequestInit = {
              method: 'POST',
              headers: { 
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
              },
            };

            // 第二个端点需要请求体
            if (endpoint === '/api/favorites') {
              requestOptions.body = JSON.stringify({
                userId: userIdNum,
                recipeId: recipeId
              });
            }

            const response = await fetch(endpoint, requestOptions);

            if (response.ok) {
              setIsFavorite(true);
              setCurrentFavoriteCount(prev => prev + 1);
              message.success('收藏成功');
              success = true;
              break;
            } else if (response.status === 400) {
              const errorText = await response.text();
              console.warn(`端点 ${endpoint} 返回400:`, errorText);
              continue;
            } else {
              console.warn(`端点 ${endpoint} 返回错误:`, response.status);
              continue;
            }
          } catch (error) {
            console.warn(`端点 ${endpoint} 请求失败:`, error);
            continue;
          }
        }

        if (!success) {
          message.error('收藏失败，请稍后重试');
        }
      }
    } catch (error) {
      message.error('操作失败');
      console.error('收藏操作异常:', error);
    } finally {
      setFavoriteLoading(false);
    }
  };

  // 跳转到作者主页
  const handleVisitAuthorPage = () => {
    if (authorInfo) {
      navigate(`/user/${authorInfo.id}`);
    }
  };

  useEffect(() => {
    console.log('RecipeDetail 渲染参数:', { id, locationState: location.state });

    if (!id) {
      setLoading(false);
      return;
    }

    // 优先使用 location.state 传递的菜谱数据
    if (location.state?.recipe) {
      const recipeData = location.state.recipe;
      console.log('从location.state接收的菜谱数据:', recipeData);
      
      const formattedRecipe: RecipeFromList = {
        id: recipeData.id || id,
        title: recipeData.title || recipeData.name || recipeData.recipeName || '未知菜谱',
        coverImage: recipeData.coverImage || recipeData.image || recipeData.photo || 'https://via.placeholder.com/400x200?text=无图',
        description: recipeData.description || recipeData.desc || '这是一道经典的家常菜，色香味俱全。',
        updatedAt: recipeData.updatedAt || recipeData.updateTime || '2025-11-24T14:56:15.07817',
        favoriteCount: recipeData.favoriteCount || recipeData.favorites || 6,
        userId: recipeData.userId || recipeData.authorId || 1,
        ...recipeData
      };
      
      console.log('格式化后的菜谱数据:', formattedRecipe);
      setRecipe(formattedRecipe);
      setCurrentFavoriteCount(formattedRecipe.favoriteCount || 0);
      setLoading(false);
      
      // 在设置菜谱数据后创建浏览记录和获取作者信息
      const recipeId = parseInt(id, 10);
      createBrowseRecord(recipeId);
      
      // 获取作者信息和检查状态
      const authorId = recipeData.userId || recipeData.authorId || 1;
      fetchAuthorInfo(authorId);
      checkFollowingStatus(authorId);
      checkFavoriteStatus(recipeId);
      return;
    }

    // 如果没有传递数据，使用兜底数据
    const fallbackRecipe: RecipeFromList = {
      id,
      title: '未知菜谱',
      coverImage: 'https://via.placeholder.com/400x200?text=无图',
      description: '',
      updatedAt: '2025-11-24T14:56:15.07817',
      favoriteCount: 6,
    };
    setRecipe(fallbackRecipe);
    setCurrentFavoriteCount(fallbackRecipe.favoriteCount || 0);
    setLoading(false);
    
    // 在设置兜底菜谱数据后创建浏览记录和获取作者信息
    const recipeId = parseInt(id, 10);
    createBrowseRecord(recipeId);
    
    // 获取默认作者信息和检查状态
    const defaultAuthorId = 1;
    fetchAuthorInfo(defaultAuthorId);
    checkFollowingStatus(defaultAuthorId);
    checkFavoriteStatus(recipeId);
  }, [id, location.state]);

  useEffect(() => {
    if (!id) return;

    const fetchAllData = async () => {
      try {
        const recipeId = parseInt(id, 10);
        const token = localStorage.getItem('token');

        if (!token) {
          message.error('请先登录');
          navigate('/login');
          return;
        }

        const [categoryRes, tagRes, ingredientRes, stepRes] = await Promise.all([
          fetch(`/api/category/by-recipe?recipeId=${recipeId}`, {
            headers: { 'Authorization': `Bearer ${token}` },
          }),
          fetch(`/api/tag/by-recipe?recipeId=${recipeId}`, {
            headers: { 'Authorization': `Bearer ${token}` },
          }),
          fetch(`/api/ingredient/by-recipe?recipeId=${recipeId}`, {
            headers: { 'Authorization': `Bearer ${token}` },
          }),
          fetch(`/api/step/recipe/${recipeId}`, {
            headers: { 'Authorization': `Bearer ${token}` },
          }),
        ]);

        if (categoryRes.ok && tagRes.ok && ingredientRes.ok && stepRes.ok) {
          const categoryData = await categoryRes.json();
          const tagData = await tagRes.json();
          const ingredientData = await ingredientRes.json();
          const stepData = await stepRes.json();

          setCategories(categoryData);
          setTags(tagData);
          setIngredients(ingredientData);
          setSteps(stepData);
        } else {
          throw new Error(`接口返回错误: ${categoryRes.status}, ${tagRes.status}, ${ingredientRes.status}, ${stepRes.status}`);
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        message.error('加载数据失败，请检查网络或登录状态');
      } finally {
        setLoading(false);
      }
    };

    fetchAllData();
  }, [id, navigate]);

  const handleBack = () => {
    navigate(-1);
  };

  if (loading) {
    return (
      <Layout style={{ 
        minHeight: '100vh', 
        backgroundImage: "url('/background2.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
      }}>
        <Sidebar />
        <Layout style={{ background: 'transparent' }}>
          <Content style={{ 
            padding: '20px', 
            textAlign: 'center', 
            paddingTop: '100px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center'
          }}>
            <Spin size="large" style={{ color: colorConfig.primary }} />
            <p style={{ marginTop: 16, color: colorConfig.primaryDark }}>
              正在加载菜谱详情...
            </p>
          </Content>
        </Layout>
      </Layout>
    );
  }

  if (!recipe) {
    return (
      <Layout style={{ 
        minHeight: '100vh', 
        backgroundImage: "url('/background2.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
      }}>
        <Sidebar />
        <Layout style={{ background: 'transparent' }}>
          <Content style={{ 
            padding: '20px', 
            textAlign: 'center', 
            paddingTop: '100px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center'
          }}>
            <h2 style={{ color: colorConfig.primaryDark, marginBottom: '20px' }}>菜谱不存在</h2>
            <Button 
              type="primary" 
              onClick={handleBack}
              style={{
                backgroundColor: colorConfig.primary,
                borderColor: colorConfig.primary,
                color: colorConfig.primaryDark,
                borderRadius: '20px',
                fontWeight: 'bold',
                padding: '8px 24px',
                height: 'auto'
              }}
            >
              返回
            </Button>
          </Content>
        </Layout>
      </Layout>
    );
  }

  const formatDate = (dateStr: string | undefined) => {
    if (!dateStr) return '未知时间';
    try {
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN');
    } catch {
      return '格式错误';
    }
  };

  return (
    <Layout style={{ 
      minHeight: '100vh', 
      backgroundImage: "url('/background2.jpg')",
      backgroundSize: 'cover',
      backgroundPosition: 'center',
    }}>
      <Sidebar />
      
      <Layout style={{ background: 'transparent' }}>
        {/* 外层容器 - 与消息页面风格一致 */}
        <div
          style={{
            margin: '20px 40px',
            background: 'white',
            borderRadius: '12px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
            display: 'flex',
            flexDirection: 'column',
            height: 'calc(100vh - 40px)',
            overflow: 'hidden'
          }}
        >
          {/* 顶部标题栏 - 优化布局确保标题完整显示 */}
          <div
            style={{
              padding: '20px 30px',
              background: 'white',
              borderBottom: `1px solid ${colorConfig.border}`,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'flex-start',
              borderRadius: '12px 12px 0 0',
              minHeight: '80px',
              gap: '20px',
            }}
          >
            {/* 标题区域 - 占据主要空间 */}
            <div style={{ 
              flex: 1, 
              minWidth: 0,
              display: 'flex',
              alignItems: 'center',
              minHeight: '40px'
            }}>
              <Title 
                level={2} 
                style={{ 
                  margin: 0, 
                  color: colorConfig.primaryDark,
                  fontSize: '24px',
                  fontWeight: 'bold',
                  wordBreak: 'break-word',
                  overflowWrap: 'break-word',
                  lineHeight: '1.3',
                  maxWidth: '100%',
                }}
              >
                {recipe.title}
              </Title>
            </div>
            
            {/* 返回按钮 - 固定宽度 */}
            <div style={{ flexShrink: 0 }}>
              <Button 
                icon={<ArrowLeftOutlined />}
                onClick={handleBack}
                style={{
                  borderRadius: '20px',
                  fontWeight: 'bold',
                  borderColor: colorConfig.border,
                  color: colorConfig.primaryDark,
                  padding: '8px 20px',
                  height: 'auto',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  whiteSpace: 'nowrap'
                }}
              >
                返回
              </Button>
            </div>
          </div>

          {/* 滚动内容区域 */}
          <div
            style={{
              flex: 1,
              overflowY: 'auto',
              padding: '24px',
              background: colorConfig.background
            }}
          >
            <Row gutter={[24, 24]}>
              {/* 作者信息卡片 */}
              <Col span={24}>
                <RecipeAuthorCard
                  authorId={recipe.userId || 1}
                  authorName={authorInfo?.username || "未知作者"}
                  avatarUrl={authorInfo?.avatar || "https://picsum.photos/50/50?random=1"}
                  onFollow={handleFollowAuthor}
                  onVisitAuthorPage={handleVisitAuthorPage}
                  isFollowing={isFollowingAuthor}
                  followLoading={followLoading}
                  colorConfig={colorConfig}
                  isCurrentUser={currentUserId && authorInfo ? parseInt(currentUserId) === authorInfo.id : false}
                />
              </Col>
            </Row>

            <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
              {/* 菜谱图片和信息 */}
              <Col xs={24} lg={12}>
                <Card
                  style={{
                    background: 'white',
                    borderRadius: '12px',
                    border: `1px solid ${colorConfig.border}`,
                    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
                    height: '100%',
                    display: 'flex',
                    flexDirection: 'column'
                  }}
                  bodyStyle={{ 
                    padding: '20px',
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column'
                  }}
                >
                  <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                    <img
                      src={getImageUrl(recipe.coverImage)}
                      alt={recipe.title}
                      style={{
                        width: '100%',
                        height: '200px',
                        objectFit: 'cover',
                        borderRadius: '8px',
                        marginBottom: '16px'
                      }}
                      onError={(e) => {
                        e.currentTarget.src = 'https://via.placeholder.com/400x200?text=无图';
                      }}
                    />
                    
                    <Title 
                      level={3} 
                      style={{ 
                        margin: '0 0 12px 0', 
                        textAlign: 'center',
                        color: colorConfig.primaryDark,
                        wordBreak: 'break-word'
                      }}
                    >
                      {recipe.title}
                    </Title>
                    
                    <Paragraph
                      style={{
                        fontSize: '14px',
                        lineHeight: '1.6',
                        color: colorConfig.primaryDark,
                        marginBottom: '16px',
                        textAlign: 'center',
                        flex: 1,
                        wordBreak: 'break-word'
                      }}
                    >
                      {recipe.description || ''}
                    </Paragraph>
                    
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'center',
                        gap: '16px',
                        flexWrap: 'wrap',
                        marginBottom: '16px'
                      }}
                    >
                      {/* 收藏计数 - 修改为使用星星图标 */}
                      <div style={{ 
                        display: 'flex', 
                        alignItems: 'center', 
                        color: colorConfig.badge,
                        fontWeight: 'bold',
                        fontSize: '14px'
                      }}>
                        <StarOutlined style={{ 
                          marginRight: '6px', 
                          color: colorConfig.badge,
                          fontSize: '16px'
                        }} />
                        {currentFavoriteCount} 收藏
                      </div>
                    </div>

                    {/* 收藏按钮 */}
                    <div style={{ textAlign: 'center', marginBottom: '16px' }}>
                      <Button 
                        type={isFavorite ? "primary" : "default"}
                        icon={isFavorite ? <StarFilled /> : <StarOutlined />}
                        loading={favoriteLoading}
                        onClick={handleFavorite}
                        style={{
                          backgroundColor: isFavorite ? '#ff4d4f' : colorConfig.primary,
                          borderColor: isFavorite ? '#ff4d4f' : colorConfig.primary,
                          color: isFavorite ? 'white' : colorConfig.primaryDark,
                          borderRadius: '20px',
                          fontWeight: 'bold',
                          padding: '8px 24px',
                          height: 'auto',
                          ...(isFavorite && {
                            backgroundColor: '#ff4d4f',
                            borderColor: '#ff4d4f',
                            color: 'white',
                            boxShadow: '0 2px 8px rgba(255,77,79,0.3)'
                          })
                        }}
                      >
                        {isFavorite ? '已收藏' : '收藏菜谱'}
                      </Button>
                    </div>
                    
                    <div
                      style={{
                        fontSize: '12px',
                        color: colorConfig.primaryDark,
                        textAlign: 'center',
                        opacity: 0.7
                      }}
                    >
                      更新于：{formatDate(recipe.updatedAt)}
                    </div>
                  </div>
                </Card>
              </Col>

              {/* 分类、标签和食材信息 */}
              <Col xs={24} lg={12}>
                <Card
                  style={{
                    background: 'white',
                    borderRadius: '12px',
                    border: `1px solid ${colorConfig.border}`,
                    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
                    height: '100%',
                    display: 'flex',
                    flexDirection: 'column'
                  }}
                  bodyStyle={{ 
                    padding: '20px',
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column'
                  }}
                >
                  <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '20px' }}>
                    {/* 分类与标签 */}
                    <div>
                      <div style={{ 
                        fontWeight: 'bold', 
                        marginBottom: '12px',
                        color: colorConfig.primaryDark,
                        fontSize: '16px'
                      }}>
                        分类与标签
                      </div>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                        {categories.map((cat) => (
                          <Tag 
                            key={cat.id} 
                            onClick={() => handleCategoryClick(cat.name)}
                            style={{
                              backgroundColor: colorConfig.primary,
                              border: 'none',
                              borderRadius: '12px',
                              color: colorConfig.primaryDark,
                              fontWeight: 'bold',
                              padding: '4px 12px',
                              cursor: 'pointer',
                              transition: 'all 0.3s',
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.backgroundColor = colorConfig.border;
                              e.currentTarget.style.transform = 'scale(1.05)';
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.backgroundColor = colorConfig.primary;
                              e.currentTarget.style.transform = 'scale(1)';
                            }}
                          >
                            {cat.name}
                          </Tag>
                        ))}
                        {tags.map((tag) => (
                          <Tag 
                            key={tag.id} 
                            onClick={() => handleTagClick(tag.name)}
                            style={{
                              backgroundColor: colorConfig.primary,
                              border: 'none',
                              borderRadius: '12px',
                              color: colorConfig.primaryDark,
                              fontWeight: 'bold',
                              padding: '4px 12px',
                              cursor: 'pointer',
                              transition: 'all 0.3s',
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.backgroundColor = colorConfig.border;
                              e.currentTarget.style.transform = 'scale(1.05)';
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.backgroundColor = colorConfig.primary;
                              e.currentTarget.style.transform = 'scale(1)';
                            }}
                          >
                            {tag.name}
                          </Tag>
                        ))}
                      </div>
                    </div>
                    
                    {/* 所需材料 */}
                    <div style={{ flex: 1 }}>
                      <div style={{ 
                        fontWeight: 'bold', 
                        marginBottom: '12px',
                        color: colorConfig.primaryDark,
                        fontSize: '16px'
                      }}>
                        所需材料
                      </div>
                      <div style={{ 
                        display: 'flex', 
                        flexDirection: 'column', 
                        gap: '8px',
                        maxHeight: '300px',
                        overflowY: 'auto'
                      }}>
                        {ingredients.map((item, i) => (
                          <div
                            key={i}
                            style={{
                              background: colorConfig.primary,
                              padding: '12px 16px',
                              borderRadius: '8px',
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              border: `1px solid ${colorConfig.border}`
                            }}
                          >
                            <span style={{ 
                              color: colorConfig.primaryDark,
                              fontWeight: '500'
                            }}>
                              {item.ingredient.name}
                            </span>
                            <span style={{ 
                              color: colorConfig.primaryDark,
                              fontWeight: 'bold'
                            }}>
                              {item.amount}{item.ingredient.unit}
                            </span>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>

            {/* 制作步骤 */}
            <Row gutter={[24, 24]}>
              <Col span={24}>
                <RecipeSteps steps={steps} colorConfig={colorConfig} />
              </Col>
            </Row>
            
            {/* 评论区域 */}
            <Row gutter={[24, 24]}>
              <Col span={24}>
                <RecipeComments 
                  recipeId={parseInt(recipe.id) || 0} 
                  colorConfig={colorConfig}
                />
              </Col>
            </Row>
          </div>
        </div>
      </Layout>
    </Layout>
  );
};

export default RecipeDetail;